<template>
  <div class="goods">
    <SearchForm
      v-model="formOption.data"
      :form-option="formOption"
      :show-arrow="true"
      :show-btn="true"
      :btn-list="btnList"
      layout="column"
      label-width="90px"
    />

    <Tabs :tabs="tabs" :current-key="currentKey" @tab-click="handleClick" />

    <div class="mb-20 flex items-center justify-between">
      <div>
        <el-button @click="batchTakeDown(true)">批量上架</el-button>
        <el-button class="ml-20" @click="batchTakeDown(false)">批量下架</el-button>
      </div>
      <el-button type="primary" @click="addGoods">新增商品</el-button>
    </div>

    <PageTable
      :columns="columns"
      :options="options"
      :data="dataSource"
      @selectChange="selectHandle"
    />
    <Pagination
      v-show="total > 0"
      :total="total"
      :pageNo.sync="listQuery.pageNo"
      :pageSize.sync="listQuery.pageSize"
      @pagination="getNewGoodsList"
    />
  </div>
</template>

<script>
import { downLoadImg } from '@/hooks'
import { RECOMMMEND_STATUS } from '@/enum'
import { ON_THE_SHELF_STATUS } from '@/enum/goods'
export default {
  name: 'GoodsList',
  data() {
    return {
      formOption: {
        data: {
          sellType: '',
          isSortCategory: ''
        },
        items: [
          {
            type: 'input',
            label: '商品名称',
            value: 'name',
            style: {
              width: '220px'
            },
            placeholder: '请输入商品名称进行搜索'
          },
          {
            type: 'daterange',
            label: '新增时间',
            value: 'time',
            valueFormat: 'yyyy-MM-dd'
          },
          {
            type: 'select',
            label: '上架状态',
            value: 'sellType',
            selectList: ON_THE_SHELF_STATUS
          },
          {
            type: 'select',
            label: '推荐状态',
            value: 'isSortCategory',
            selectList: RECOMMMEND_STATUS
          }
        ]
      },
      btnList: [
        {
          type: 'primary',
          label: '筛选',
          onClick: () => {
            this.listQuery.pageNo = 1
            this.getNewGoodsList()
          }
        },
        {
          label: '重置',
          onClick: () => {
            this.formOption.data = {}
            this.listQuery.pageNo = 1
            this.getNewGoodsList()
          }
        }
      ],
      listQuery: {
        pageNo: 1,
        pageSize: 10
      },
      total: 0,
      currentKey: 'total',
      selectList: [],
      options: {
        select: true,
        border: true
      },
      dataSource: [],
      columns: [
        {
          label: '商品名称',
          width: '160px',
          render: (h, { row }) => {
            return (
              <div style={'display: flex'}>
                <div class="flex flex-col">
                  <el-image
                    style={'width: 60px;height: 60px;'}
                    src={row.mainGraph}
                    previewSrcList={[row.mainGraph]}
                  />
                  <el-popover
                    placement="bottom"
                    title="商品二维码"
                    width="200"
                    trigger="click"
                    onHide={() => {
                      this.showQrCode = ''
                    }}
                  >
                    <div class="flex-col flex align-center">
                      {this.showQrCode ? (
                        <img style={'width: 85px;height: 85px;'} src={this.showQrCode} />
                      ) : (
                        <span>加载中...</span>
                      )}

                      <p class="mt-5">扫码后直接访问商品</p>
                      <el-link
                        class="mt-5 ft-12"
                        underline={false}
                        type="primary"
                        onClick={() => downLoadImg(row.name, this.showQrCode)}
                      >
                        下载二维码
                      </el-link>
                    </div>
                    <el-link
                      class="ft-12"
                      underline={false}
                      type="primary"
                      slot="reference"
                      onClick={() => this.getQrcode(row)}
                    >
                      商品二维码
                    </el-link>
                  </el-popover>
                </div>
                <p class="goodsNameClass ml-5" style="color:#409eff">
                  {row.name}
                </p>
              </div>
            )
          }
        },
        {
          label: '积分兑换',
          render: (h, { row }) => {
            return <div>{`${row.minPrice}-${row.maxPrice}`}</div>
          }
        },
        {
          prop: 'validStockQuantity',
          label: '库存'
        },
        {
          prop: 'sort',
          label: '排序值'
        },
        {
          label: '配送方式',
          render: () => {
            return <el-button type="text">快递配送</el-button>
          }
        },
        {
          prop: 'createdTime',
          label: '新增时间'
        },
        {
          label: '上架状态',
          render: (h, { row }) => {
            return (
              <span style={row.platformState ? 'color: #409eff' : ''}>
                {!row.platformState ? '仓库中' : '已上架'}
              </span>
            )
          }
        },
        {
          label: '操作',
          width: '180px',
          render: (h, { row }) => {
            return (
              <div>
                {row.platformState ? (
                  <el-button type="text" onClick={() => this.updatedUnloadingState(row)}>
                    下架
                  </el-button>
                ) : (
                  <el-button type="text" onClick={() => this.updatedUnloadingState(row)}>
                    上架
                  </el-button>
                )}
                <el-button type="text" onClick={() => this.editGoods(row.id)}>
                  编辑
                </el-button>
                {row.isSortCategory ? (
                  <el-button type="text" onClick={() => this.updatedRecommend(row)}>
                    取消推荐
                  </el-button>
                ) : (
                  <el-button type="text" onClick={() => this.updatedRecommend(row)}>
                    推荐
                  </el-button>
                )}
                {!row.platformState ? (
                  <PopConfirm text="确定删除该商品吗？" confirm={() => this.deleteNewGoods(row.id)}>
                    <el-button class="ml-10" type="text">
                      删除
                    </el-button>
                  </PopConfirm>
                ) : (
                  ''
                )}
              </div>
            )
          }
        }
      ],
      showQrCode: '',
      tabs: []
    }
  },
  computed: {
    ids() {
      return this.selectList.map(item => item.id)
    }
  },
  created() {
    this.getNewGoodsList()
  },
  methods: {
    // tab切换
    handleClick({ key, value }) {
      this.currentKey = key
      this.formOption.data.sellType = value
      this.listQuery.pageNo = 1
      this.getNewGoodsList()
    },
    // 获取商品列表
    async getNewGoodsList() {
      const params = {
        ...this.listQuery,
        ...this.formOption.data
      }
      const { time } = this.formOption.data
      if (time) params.startCreateTime = time[0] && time[0]
      if (time) params.endCreateTime = time[1] && time[1]
      delete params.time
      const {
        data: { total, totalNotSell, totalSellFinished, totalSelling, records }
      } = await this.$http.goods.newcomer.getNewGoodsList(params)
      this.total = total
      this.dataSource = records

      // 获取统计数量
      const tabsData = {
        total,
        totalSelling,
        totalNotSell,
        totalSellFinished
      }
      this.tabs = ON_THE_SHELF_STATUS.map(item => {
        for (const key in tabsData) {
          if (item.key === key) {
            item.num = tabsData[key]
          }
        }
        return item
      })
    },
    // 点击查看商品二维码
    async getQrcode({ id }) {
      const { data } = await this.$http.goods.goods.createQrcodeById({
        autoColor: true,
        goodsId: id,
        isHyaline: true,
        lineColor: { r: '0', g: '0', b: '0' },
        page: '',
        width: 280
      })
      this.showQrCode = data
    },
    // 选择商品
    selectHandle(val) {
      this.selectList = val
    },
    // 上下架
    async updatedUnloadingState({ id, platformState }) {
      let message = platformState == 2 ? '已下架' : '已上架'
      let isState = platformState == 2 ? false : true
      const { status, msg } = await this.$http.goods.newcomer.updatedUnloadingState(id, isState)
      if (status === 200) {
        this.$message.success(message)
        this.getNewGoodsList()
      } else {
        this.$message.error(msg)
      }
    },
    // 推荐不推荐
    async updatedRecommend({ id, isSortCategory }) {
      let message = isSortCategory ? '已取消推荐' : '已推荐'
      const { status, msg } = await this.$http.goods.newcomer.updatedRecommend({
        id,
        isRecommend: !isSortCategory
      })
      if (status === 200) {
        this.$message.success(message)
        this.getNewGoodsList()
      } else {
        this.$message.error(msg)
      }
    },
    // 批量上下架
    async batchTakeDown(state) {
      let message = state ? '上架' : '下架'
      if (!this.selectList.length) return this.$message.error(`请选择${message}的商品`)
      const { status, msg } = await this.$http.goods.newcomer.batchShelf({ state, ids: this.ids })
      if (status === 200) {
        this.$message.success(`已批量${message}！`)
        this.getNewGoodsList()
      } else {
        this.$message.error(msg)
      }
    },
    // 删除
    async deleteNewGoods(id) {
      const { status, msg } = await this.$http.goods.newcomer.deleteNewGoods(id)
      if (status === 200) {
        this.$message.success('已删除！')
        this.getNewGoodsList()
      } else {
        this.$message.error(msg)
      }
    },
    // 新增商品
    addGoods() {
      this.$router.push({ name: 'AddGoods' })
    },
    // 编辑商品
    editGoods(id) {
      this.$router.push({ name: 'EditGoods', query: { id } })
    }
  }
}
</script>

<style lang="scss">
.goodsImg {
  position: relative;
  width: 60px;
  height: 60px;
}
.goodsTip {
  position: absolute;
  top: 30px;
  left: 6px;
  font-size: 12px;
  color: #fff;
  line-height: 20px;
  background-color: #fc4541;
}
.goodsTitle {
  color: #409eff;
  @include ellipsis(4);
}
.goodsNameClass {
  @include ellipsis(4);
}
</style>
